$(function(){
	var baseUrl="https://gzflower.bluej.cn/";
	var get_res; //保存预约列表反回值
	
	var api={
		enter:baseUrl+"index/book/book", //进入预约
		chooselist:baseUrl+"index/choose/chooselist", //获取预约列表
		chooseday:baseUrl+"index/choose/chooseday", //查询某天场次
		bookday:baseUrl+"index/choose/bookday", //预约某天场次
		
		getDay:function(day){
			var str = '2019-'+day.replace(/['月']/g,'-');
			var new_day = str.slice(0,-1);
			return new_day;
		}
	}
	
	//进入预约
	$('#btn1').click(function(){
		var uname = $('#uname').val();
		var phone = $('#phone').val();
		var idcard = $('#idcard').val();
		$.ajax({
			type:"post",
			url:api.enter,
			async:true,
			data:{
				"phone_num":phone,
				"idcard_num":idcard,
				"uname":uname
			},
			success:function(res){
				console.log(res)
				var token=res.data.access_token;
				localStorage.setItem('token',token)
				if(res.res==1){
					setTimeout(function(){
						window.location.href='yuyue.html';
					},2000)
				}
			},
			error:function(e){
				console.log('错误',e)
			}
		});
		
	})
	
	//获取预约列表
	$('select').change(function(){
		var day = $('select').val();
		var token = localStorage.getItem('token');
		$.ajax({
			type:"post",
			url:api.chooseday,
			async:true,
			data:{
				"access_token":token,
				"day_time":api.getDay(day)
			},
			success:function(res){
				get_res = res;
				console.log('res',res)
				var balance,txt;
				$('.p').each(function(index,ele){
					//判断是否有场次
					if(res.data.dayInfo[index]){
						balance = res.data.dayInfo[index].balance;
					}else{
						balance = null;
					}
					
					if(balance!=0){
						$($('.p')[index]).text('可预约');
					}
					if(balance==0){
						$($('.p')[index]).text('已约满');
					}
					if(balance==null){
						$($('.p')[index]).text('无');
					}
				})
			},
			error:function(e){
				console.log('错误',e)
			}
		})			
	})
	
	//预约场次
	$('.p').each(function(index,ele){
		$($('.p')[index]).click(function(){
			var txt = $($('.p')[index]).text();
			if(txt=='可预约'){
				var token = localStorage.getItem('token');
				var day_time = get_res.data.dayInfo[index].day_time;
				
				var show_id = get_res.data.dayInfo[index].show_id;
				$.ajax({
					type:"post",
					url:api.bookday,
					async:true,
					data:{
						"access_token":token,
						"day_time":day_time,
						"show_id":show_id
					},
					success:function(res){
						console.log('restime',res)
						if(res.res==1){
							alert("预约成功");
							var prev_txt = $($('.p')[index]).prev().text();
							var start_time = prev_txt.slice(0,5);
							localStorage.setItem('start_time',start_time);
							localStorage.setItem('show_id',res.data.show_id);
							localStorage.setItem('day_time',res.data.day_time);
							localStorage.setItem('uname',res.data.uname);
							window.location.href='ewm.html';
						}else{
							alert("一天只可以预约一次")
						}
					},
					error:function(e){
						console.log('错误',e)
					}
				})
			}
			if(txt=='已约满'){
				alert('人数已满，请预约其他场次！');
			}
		});
	})
	

})